<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商户管理</title>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/bootstrap-table/1.18.3/bootstrap-table.min.css">
    <style>
        .gray-bg {
            background-color: #f8f9fa;
        }
        .container-div {
            padding: 20px;
        }
        .search-collapse {
            margin-bottom: 15px;
            background-color: #fff;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,.1);
        }
        .select-list ul {
            margin: 0;
            padding: 0;
            list-style: none;
        }
        .select-list li {
            display: inline-block;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        .btn-group-sm {
            margin-bottom: 15px;
        }
        .select-table {
            background-color: #fff;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0,0,0,.1);
        }
        .badge-success {
            background-color: #28a745;
        }
        .badge-danger {
            background-color: #dc3545;
        }
    </style>
</head>
<body class="gray-bg">
    <div class="container-div">
        <div class="row">
            <div class="col-sm-12 search-collapse">
                <form id="merchant-form">
                    <div class="select-list">
                        <ul>
                            <li>
                                商户名称：<input type="text" name="merchantName"/>
                            </li>
                            <li>
                                商户类型：
                                <select name="merchantType">
                                    <option value="">所有</option>
                                    <option value="0">类型1</option>
                                    <option value="1">类型2</option>
                                </select>
                            </li>
                            <li>
                                状态：
                                <select name="status">
                                    <option value="">所有</option>
                                    <option value="0">正常</option>
                                    <option value="1">停用</option>
                                </select>
                            </li>
                            <li>
                                <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i> 搜索</a>
                                <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i> 重置</a>
                            </li>
                        </ul>
                    </div>
                </form>
            </div>

            <div class="btn-group-sm" id="toolbar" role="group">
                <a class="btn btn-success" onclick="$.operate.add()">
                    <i class="fa fa-plus"></i> 新增
                </a>
                <a class="btn btn-primary" onclick="$.operate.edit()">
                    <i class="fa fa-edit"></i> 修改
                </a>
                <a class="btn btn-danger" onclick="$.operate.removeAll()">
                    <i class="fa fa-trash"></i> 删除
                </a>
            </div>

            <div class="col-sm-12 select-table table-striped">
                <table id="bootstrap-table"></table>
            </div>
        </div>
    </div>

    <!-- 添加或修改商户对话框 -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="myModalLabel">添加商户</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" id="form-merchant-add">
                        <input type="hidden" id="merchantId" name="merchantId">
                        <div class="form-group">
                            <label class="col-sm-3 control-label is-required">商户名称：</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" id="merchantName" name="merchantName" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">商户类型：</label>
                            <div class="col-sm-8">
                                <select class="form-control" id="merchantType" name="merchantType">
                                    <option value="0">类型1</option>
                                    <option value="1">类型2</option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">联系人：</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" id="contactName" name="contactName">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">联系电话：</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" id="contactPhone" name="contactPhone">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">联系邮箱：</label>
                            <div class="col-sm-8">
                                <input type="email" class="form-control" id="contactEmail" name="contactEmail">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">地址：</label>
                            <div class="col-sm-8">
                                <input type="text" class="form-control" id="address" name="address">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">经营范围：</label>
                            <div class="col-sm-8">
                                <textarea class="form-control" id="businessScope" name="businessScope"></textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">状态：</label>
                            <div class="col-sm-8">
                                <div class="radio-box">
                                    <input type="radio" id="status_0" name="status" value="0" checked>
                                    <label for="status_0">正常</label>
                                </div>
                                <div class="radio-box">
                                    <input type="radio" id="status_1" name="status" value="1">
                                    <label for="status_1">停用</label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-3 control-label">备注：</label>
                            <div class="col-sm-8">
                                <textarea class="form-control" id="remark" name="remark"></textarea>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="btn-save">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap-table/1.18.3/bootstrap-table.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap-table/1.18.3/locale/bootstrap-table-zh-CN.min.js"></script>
    
    <script>
        // 初始化函数，可以被外部调用
        function initMerchantTable() {
            // 确保bootstrap-table已加载
            if (typeof $.fn.bootstrapTable === 'undefined') {
                console.error('Bootstrap Table plugin is not loaded!');
                // 尝试重新加载bootstrap-table
                loadScript('https://cdn.bootcdn.net/ajax/libs/bootstrap-table/1.18.3/bootstrap-table.min.js', function() {
                    loadScript('https://cdn.bootcdn.net/ajax/libs/bootstrap-table/1.18.3/locale/bootstrap-table-zh-CN.min.js', function() {
                        // 重新调用初始化函数
                        setTimeout(initMerchantTable, 100);
                    });
                });
                return;
            }
            
            var prefix = "/business/merchant";
            
            // 定义通用对象
            $.table = {
                init: function(options) {
                    $('#bootstrap-table').bootstrapTable(options);
                },
                refresh: function() {
                    $('#bootstrap-table').bootstrapTable('refresh');
                },
                search: function() {
                    $('#bootstrap-table').bootstrapTable('refresh');
                }
            };
            
            $.form = {
                reset: function() {
                    $('#merchant-form')[0].reset();
                    $('#bootstrap-table').bootstrapTable('refresh');
                }
            };
            
            $.operate = {
                add: function() {
                    $("#merchantId").val("");
                    $("#merchantName").val("");
                    $("#merchantType").val("0");
                    $("#contactName").val("");
                    $("#contactPhone").val("");
                    $("#contactEmail").val("");
                    $("#address").val("");
                    $("#businessScope").val("");
                    $("#status_0").prop("checked", true);
                    $("#remark").val("");
                    $("#myModalLabel").text("添加商户");
                    $("#myModal").modal("show");
                },
                edit: function(id) {
                    $.ajax({
                        url: prefix + "/" + id,
                        type: "GET",
                        dataType: "json",
                        success: function(result) {
                            if (result.code == 200) {
                                var data = result.data;
                                $("#merchantId").val(data.merchantId);
                                $("#merchantName").val(data.merchantName);
                                $("#merchantType").val(data.merchantType);
                                $("#contactName").val(data.contactName);
                                $("#contactPhone").val(data.contactPhone);
                                $("#contactEmail").val(data.contactEmail);
                                $("#address").val(data.address);
                                $("#businessScope").val(data.businessScope);
                                $("input[name='status'][value='" + data.status + "']").prop("checked", true);
                                $("#remark").val(data.remark);
                                $("#myModalLabel").text("修改商户");
                                $("#myModal").modal("show");
                            } else {
                                alert(result.msg);
                            }
                        }
                    });
                },
                remove: function(id) {
                    if (confirm("确认要删除选中的记录吗?")) {
                        $.ajax({
                            url: prefix + "/" + id,
                            type: "DELETE",
                            dataType: "json",
                            success: function(result) {
                                if (result.code == 200) {
                                    $('#bootstrap-table').bootstrapTable('refresh');
                                } else {
                                    alert(result.msg);
                                }
                            }
                        });
                    }
                },
                removeAll: function() {
                    var rows = $('#bootstrap-table').bootstrapTable('getSelections');
                    if (rows.length == 0) {
                        alert("请至少选择一条记录");
                        return;
                    }
                    
                    var ids = [];
                    $.each(rows, function(i, row) {
                        ids.push(row.merchantId);
                    });
                    
                    if (confirm("确认要删除选中的" + ids.length + "条记录吗?")) {
                        $.ajax({
                            url: prefix + "/" + ids.join(","),
                            type: "DELETE",
                            dataType: "json",
                            success: function(result) {
                                if (result.code == 200) {
                                    $('#bootstrap-table').bootstrapTable('refresh');
                                } else {
                                    alert(result.msg);
                                }
                            }
                        });
                    }
                }
            };
            
            var options = {
                url: prefix + "/list",
                createUrl: prefix,
                updateUrl: prefix,
                removeUrl: prefix + "/{id}",
                modalName: "商户",
                method: 'get',
                dataType: 'json',
                contentType: "application/json",
                pagination: true,
                queryParams: function(params) {
                    var search = {};
                    $.each($('#merchant-form').serializeArray(), function(i, field) {
                        search[field.name] = field.value;
                    });
                    search.pageSize = params.limit;
                    search.pageNum = params.offset / params.limit + 1;
                    if (isNaN(search.pageNum)) {
                        search.pageNum = 1; // Default to page 1 if calculation results in NaN
                    }
                    search.orderByColumn = params.sort;
                    search.isAsc = params.order;
                    return search;
                },
                columns: [
                    {checkbox: true},
                    {field: 'merchantId', title: '商户ID'},
                    {field: 'merchantName', title: '商户名称'},
                    {field: 'merchantType', title: '商户类型', formatter: function(value, row, index) {
                        return value == '0' ? '类型1' : '类型2';
                    }},
                    {field: 'contactName', title: '联系人'},
                    {field: 'contactPhone', title: '联系电话'},
                    {field: 'address', title: '地址'},
                    {field: 'status', title: '状态', formatter: function(value, row, index) {
                        return value == '0' ? '<span class="badge badge-success">正常</span>' : 
                            '<span class="badge badge-danger">停用</span>';
                    }},
                    {field: 'createTime', title: '创建时间'},
                    {title: '操作', align: 'center', formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.merchantId + '\')"><i class="fa fa-edit"></i>编辑</a> ');
                        actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.merchantId + '\')"><i class="fa fa-remove"></i>删除</a>');
                        return actions.join('');
                    }}
                ],
                responseHandler: function(res) {
                    return {
                        "total": res.data.total,
                        "rows": res.data.records
                    };
                }
            };
            
            // 初始化表格
            $('#bootstrap-table').bootstrapTable(options);

            // 保存按钮点击事件
            $("#btn-save").click(function() {
                var merchantId = $("#merchantId").val();
                var url = merchantId ? prefix : prefix;
                var method = merchantId ? "PUT" : "POST";
                
                $.ajax({
                    url: url,
                    type: method,
                    contentType: "application/json",
                    data: JSON.stringify({
                        merchantId: merchantId,
                        merchantName: $("#merchantName").val(),
                        merchantType: $("#merchantType").val(),
                        contactName: $("#contactName").val(),
                        contactPhone: $("#contactPhone").val(),
                        contactEmail: $("#contactEmail").val(),
                        address: $("#address").val(),
                        businessScope: $("#businessScope").val(),
                        status: $("input[name='status']:checked").val(),
                        remark: $("#remark").val()
                    }),
                    success: function(result) {
                        if (result.code == 200) {
                            $("#myModal").modal("hide");
                            $('#bootstrap-table').bootstrapTable('refresh');
                        } else {
                            alert(result.msg);
                        }
                    }
                });
            });
        }

        // 加载脚本的辅助函数
        function loadScript(url, callback) {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = url;
            script.onload = callback;
            document.head.appendChild(script);
        }

        // 确保页面完全加载后再执行脚本
        $(document).ready(function() {
            initMerchantTable();
        });
        
        // 监听document的ready事件，以便外部触发
        $(document).on('ready', function() {
            initMerchantTable();
        });
    </script>
</body>
</html> 